#!/bin/bash
BASE_HOME=$(dirname "$0")
source ${BASE_HOME}/common_setup  # Loading the common code section from 'common_setup', and 'common_setup' in turn loads the shared functions from 'common_functions'.

log_info "Keepalived transitioning to backup status, configuring local MySQL database slave if not already set."

## Check if the write VIP exists on this node, and determine whether to continue configuring this node as a slave 
WVIP_COUNT=`ip addr | grep -v grep | grep "${WRITE_VIP}" |wc -l`
if [ ${WVIP_COUNT} -eq 1 ]; then
    log_info "VIP ${WRITE_VIP} exists on local host ${LOCAL_HOST}. MySQL node is master, no need to configure as slave."
    log_info "VIP details: `ip addr | grep -v grep | grep \"${WRITE_VIP}\"`"
    log_info "Keepalived ending backup status, exiting script execution."
    exit 0
else
    log_warn "VIP ${WRITE_VIP} not found on local host ${LOCAL_HOST}. MySQL node is slave, continuing with slave configuration."
fi

## Check if VIP is reachable by ping
remote_host_ping_vip()
{
    result_ping=0
    ping -c ${PINGDOWN_C} ${WRITE_VIP} 
    if (( $? == 0 )); then
        result_ping=1
    else
        result_ping=0
    fi
}

log_info "Local host ${LOCAL_HOST} is pinging VIP with: ping -c ${PINGDOWN_C} ${WRITE_VIP}"
i=1
down_time=0
while [ ${i} -le ${PINGDOWN_TOTAL} ]
do
    remote_host_ping_vip
    if [ ${result_ping} -eq 1 ]; then
        log_info "Local host ${LOCAL_HOST} is able to reach VIP ${WRITE_VIP}. Attempt number: ${i}"
        down_time=1
    else
        log_info "Local host ${LOCAL_HOST} unable to reach VIP ${WRITE_VIP}. Attempt number: ${i}"
        down_time=0
        break;
    fi
    i=$(($i+1))
done
log_info "End of VIP ping attempts: ping -c ${PINGDOWN_C} ${WRITE_VIP}"

if [ ${down_time} -eq 1 ]; then
    log_info "Local host ${LOCAL_HOST} can reach VIP ${WRITE_VIP}. Continuing with slave policy configuration."
else
    log_warn "Local host ${LOCAL_HOST} cannot reach VIP ${WRITE_VIP}. No need to set slave policy."
    log_info "Keepalived ending backup status, exiting script execution."
    exit 0
fi 
 
# Create binlog parse to SQL work directory if it doesn't exist
[ ! -d ${sqlpath} ] && mkdir -p ${sqlpath} 

# Check if the remote MySQL is alive using mysqladmin ping
alive_string=`${MYSQLPING_REMOTE_CMD}`

if [ "${alive_string}" != "mysqld is alive" ]; then
    log_warn "Remote MySQL on host ${REMOTE_HOST} is not alive: ${alive_string}"
    log_info "Backup status ended by keepalived. Exiting script."
    exit 0
else
    log_warn "Remote MySQL on host ${REMOTE_HOST} is alive: ${alive_string}. Checking if it is master."
    slave_string=`${MYSQL_REMOTE_CMD} -N -L -s -e "show slave status"`
    log_warn "MySQL slave info on remote host ${REMOTE_HOST}: ${slave_string}"   
    if [ -n "${slave_string}" ]; then
        log_warn "Remote host ${REMOTE_HOST} is a slave and doesn't require slave configuration."
        log_info "Backup status ended by keepalived. Exiting script."
        exit 0
    else
        log_info "Remote host ${REMOTE_HOST} is in master role. Continue to set slave policy."
    fi
fi

log_info "Fetching local MySQL slave status..."
${MYSQL_LOCAL_CMD} -e "show slave status \G" > ${sqlpath}/local_slave.txt

if (( $? == 0 )); then
    cat ${sqlpath}/local_slave.txt
    log_info "Successfully got \`show slave status\`."
    slave_host=`grep -w "Master_Host" ${sqlpath}/local_slave.txt | awk -F": " '{print $2}'`   
    if [ -n "${slave_host}" ]; then
        log_info "Local host is already configured as slave with Master_Host=${slave_host}"
    else
        log_warn "Local host is not yet configured as slave. Master_Host=${slave_host}"
        log_info "Starting slave configuration for local host..."
        ${MYSQL_LOCAL_CMD} -N -L -s -e "set  global super_read_only=OFF;set global read_only=ON;show variables like '%read_only';"
        ${MYSQL_LOCAL_CMD} -e "CHANGE MASTER TO MASTER_HOST = '${REMOTE_HOST}', MASTER_USER = '${REP_USER}', MASTER_PASSWORD = '${REP_PWD}',MASTER_PORT=${MYSQL_PORT},MASTER_AUTO_POSITION = 1;reset slave;start slave;"        
        if (( $? == 0 )); then
            log_info "Slave configuration completed for local host."
            ${MYSQL_LOCAL_CMD} -e "set global super_read_only=ON;show variables like 'super_read_only';show variables like 'read_only';show slave status \G"
        else
            log_warn "Failed to configure local host as slave."
        fi
    fi
    rm -f ${sqlpath}/local_slave.txt
else
    log_warn "Failed to fetch local MySQL slave status."
fi

log_info "Backup status ended by keepalived. Exiting script."